//
//  HMUserAccount.swift
//  Weibo-swift
//
//  Created by GD on 16/9/22.
//  Copyright © 2016年 geduo. All rights reserved.
//

import UIKit

let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archiver")

class HMUserAccount: NSObject, NSCoding {
    var access_token: String?//用户授权的唯一票据
    var expires_in:TimeInterval = 0{//access_token的生命周期
        didSet{
            expiresDate = Date().addingTimeInterval(expires_in)
        }
    }
    var uid: Int64 = 0//授权用户的UID
    
    //过期时间
    var expiresDate: Date?
    
    //用户头像
    var profile_image_url:String?
    
    //用户名
    var name: String?
    
    //kVC 构造函数
    init(dict:[String:Any]) {
        super.init()
        
        setValuesForKeys(dict)
    }
    
    //防奔溃
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
    // MARK : -- 归档 解档
    func encode(with enoder: NSCoder) {
        enoder.encode(access_token, forKey: "access_token")
        enoder.encode(expiresDate, forKey: "expiresDate")
        
        enoder.encode(uid, forKey: "uid")
        enoder.encode(name, forKey: "name")
        enoder.encode(profile_image_url, forKey: "profile_image_url")
        
    }
    
    required init?(coder decoder: NSCoder) {
        access_token = decoder.decodeObject(forKey: "access_token") as! String?
        expiresDate = decoder.decodeObject(forKey: "expiresDate") as! Date?
        uid = decoder.decodeInt64(forKey: "uid")
        name = decoder.decodeObject(forKey: "name") as? String
        profile_image_url = decoder.decodeObject(forKey: "profile_image_url") as? String
    }
    
    //保存当前用户对象
    func saveUserAccount() -> () {

        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
    
    //从指定沙盒路径获取用户对象
    class func loadUserAccount() -> HMUserAccount? {
        return NSKeyedUnarchiver.unarchiveObject(withFile: path) as? HMUserAccount
    }
}
